function getObjKeyByValue(object: Object, value: unknown) {
	for (const prop in object) {
		if (object.hasOwnProperty(prop)) {
			if (object[prop] === value) {
				return prop;
			}
		}
	}
	return '';
}

function getEuiObjKey(e: egret.DisplayObject) {
	let f = e.parent;
	while (f) {
		const key = getObjKeyByValue(f, e);
		if (key) {
			return [f, key];
		}
		f = f.parent;
	}
	return [null, ''];
}

class MainClick extends eui.UILayer {
	click: egret.MovieClip;

	Main: egret.DisplayObject;

	clicktarget: any;

	constructor(Main: egret.DisplayObject) {
		super();
		this.Main = Main;
		Main.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap, this);
	}

	onTap(evt: egret.TouchEvent): void {
		const mouseevent = curMouseEvent();
		if (isDebug()) {
			console.log('MainClick.onTap:', evt.target, mouseevent);
			const t = evt.target;
			const [p, key] = getEuiObjKey(t); // 没法得到，必须是dlg一级才有name！
			if (p) {
				ui.msglog(`MainClick.onTap: ${p.constructor.name}.${key}(${t.constructor.name})`);
			} else {
				ui.msglog(
					`MainClick.onTap: t: ${t.constructor.name} t.parent: ${t.parent.constructor.name}`,
				);
			}
		}
		// this.focus.setFocusTarget(evt.target)
		this.setClick(evt.stageX, evt.stageY, evt.target);
	}

	async setClick(x: number, y: number, target: any): Promise<void> {
		if (!this.click) {
			const click = await ui.getClick().CreateClick(target);
			if (!click) {
				return;
			}
			//if (target !== game.GameMap.ins()) {
				this.addChild(click);
			//}

			click.addEventListener(
				egret.Event.COMPLETE,
				() => {
					// console.log("click egret.Event.COMPLETE")
					click.visible = false;
				},
				null,
			);
			this.clicktarget = target;
			this.click = click;
		}
		if (this.clicktarget !== target) {
			const click = await ui.getClick().CreateClick(target);
			if (!click) {
				return;
			}
			//if (target !== game.GameMap.ins()) {
				this.addChild(click);
			//}
			click.addEventListener(
				egret.Event.COMPLETE,
				() => {
					// console.log("click egret.Event.COMPLETE")
					click.visible = false;
				},
				null,
			);
			this.clicktarget = target;
			this.click = click;
		}
		this.click.x = x;
		this.click.y = y;
		this.click.gotoAndPlay(0, 1);
		this.click.visible = true;
	}
}
